import os
import requests


def getPage(url, pageName):
    if not os.path.exists('pages'):
        os.mkdir('pages')

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0',
    }

    response = requests.get(
        url=url, headers=headers).content.decode(encoding='utf-8')

    fw = open(os.path.join('pages', pageName), 'w', encoding='utf-8')
    fw.write(response)
    fw.close()

    return


def download():
    if not os.path.exists('video-audio'):
        os.mkdir('video-audio')

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0',
        "Origin": 'https://www.kugou.com/',
        "Referer": 'https://www.kugou.com/'
    }

    urls = ['https://webfs.cloud.kugou.com/202205040838/4e07482dc6cd1f8be767355c391ccce1/KGTX/CLTX001/80cc2f0141d7d0109a1bec06cfee8caf.mp3']

    for i, url in enumerate(urls):
        try:
            response = requests.get(url, headers=headers,
                                    stream=True, verify=True)
            print(response.status_code)
            fileName = os.path.join('video-audio', "{}.mp3".format(i))
            with open(fileName, 'wb') as fw:
                for chunk in response.iter_content(1024):
                    fw.write(chunk)
                    fw.flush()  # 清空缓存
        except Exception as e:
            print("url下载错误：%s" % url)
            print(e)

    return


if __name__ == '__main__':

    # use
    # url = 'https://www.bilibili.com/video/BV1kJ411K7bx'
    # getPage(url=url, pageName='8d.html')
    download()
